package com.shxc.smarttrade.old.foreignfragment;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.utils.Utils;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.quotation.old.AllQuotationActivity;
import com.shxc.smarttrade.old.adapter.ViewPagerAdapter;
import com.shxc.smarttrade.old.bean.OpenTrader;
import com.shxc.smarttrade.old.bean.PendingOrder;
import com.shxc.smarttrade.old.bean.RealTimeQuoteDatas;
import com.shxc.smarttrade.old.bean.StockChartDatas;
import com.shxc.smarttrade.old.bean.SymbolInfo;
import com.shxc.smarttrade.old.bean.SymbolPrice;
import com.shxc.smarttrade.old.iview.ISimpleTradeFragment;
import com.shxc.smarttrade.old.myview.MyProgressDialog;
import com.shxc.smarttrade.old.presenter.SimpleTradePresenter;
import com.shxc.smarttrade.old.utils.Arith;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.shxc.smarttrade.utils.Loger;
import com.umeng.analytics.MobclickAgent;
import com.wordplat.ikvstockchart.InteractiveKLineView;
import com.wordplat.ikvstockchart.drawing.HighlightDrawing;
import com.wordplat.ikvstockchart.entry.Entry;
import com.wordplat.ikvstockchart.entry.EntrySet;
import com.wordplat.ikvstockchart.marker.XAxisTextMarkerView;
import com.wordplat.ikvstockchart.marker.YAxisTextMarkerView;
import com.wordplat.ikvstockchart.render.KLineRender;
import com.wordplat.ikvstockchart.render.TimeLineRender;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * Created by jcdev1 on 2017/10/27.
 */

public class AdvancedTransFragment extends Fragment implements ISimpleTradeFragment {


    @BindView(R.id.tv_ch_name)
    TextView tvChName;
    @BindView(R.id.tv_cn_name)
    TextView tvCnName;
    @BindView(R.id.tv_mark_price)
    TextView tvMarkPrice;
    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;
    @BindView(R.id.iv_arrow_right)
    ImageView ivArrowRight;
    @BindView(R.id.k_line)
    InteractiveKLineView kLine;
    @BindView(R.id.magic_indicator_botton)
    MagicIndicator magicIndicatorBotton;
    @BindView(R.id.view_pager)
    ViewPager viewPager;


    private View rootView;

    private boolean isGetKData = false;//判断是否获取到K线图数据
    private List<StockChartDatas.DataBean.QuotesBean> qb;
    private long oldTime;//报价时间
    private double oldOpenPrice;//开盘价（某个时间段的）
    private double oldHigt;//最高价（某个时间段的）
    private double oldLow;//最低价（某个时间段的）
    private double oldClose;//收盘价（某个时间段的）
    private int realDataSize = 0;//真实K线图或分时图集合大小
    private int timeLineTag = 0;//用于判断是日分时还是分时 0：日分时 1:分k线图 2：日K图
    private boolean isKLine = false;//当前展示的是否为K线图
    private int digits = 5;//价格小数位数
    private int oldPosition = 0;//记录当前K线所属
    private long timeDiff;//记录不同时间差
    private MyProgressDialog shortDialog;
    private String symbolK;
    private AllQuotationActivity activity;
    private double yestodayClosePrice = -1;//昨日收盘价


    private static final String[] tabName = {"分时", "日线", "周线", "1分钟", "5分钟", "15分钟", "30分钟", "1小时", "4小时", "月线"};
    private List<String> mDataList = Arrays.asList(tabName);

    private static final String[] tabNameButtom = {"市价", "挂单"};
    private List<String> mDataListButtom = Arrays.asList(tabNameButtom);

    private SimpleTradePresenter presenter;
    private String accessToken = "";
    private MarketAndPendingControlFragment marketAndPendingControlFragment;
    private MarketPriceFragment marketPriceFragment;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.advanced_trans_fragment, null);
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        ButterKnife.bind(this, rootView);
//        EventBus.getDefault().register(this);
        initView();

        initData();
        return rootView;
    }



    private void initData() {
        activity = (AllQuotationActivity) getActivity();//第一行
        digits = activity.digits;
        accessToken = SpUtils.getString(getActivity(), "accessToken", "");
        presenter = new SimpleTradePresenter(this);
        timeDiff = 1000 * 60;
        symbolK = activity.symbleOne;//用于请求K线图的产品名称
        tvChName.setText(activity.symbolCn);
        tvCnName.setText(activity.symbleOne);
        presenter.getStockChartData(accessToken, symbolK, "0", 0);

    }

    private void initView() {
        initMagicIndicator();
        initMagicIndicatorBottom();
    }

    private void initMagicIndicatorBottom() {

        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(marketPriceFragment = new MarketPriceFragment());
        fragmentList.add(marketAndPendingControlFragment = new MarketAndPendingControlFragment());

        viewPager.setOffscreenPageLimit(2);
        viewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager(), fragmentList));
        final CommonNavigator commonNavigator = new CommonNavigator(getActivity());
        commonNavigator.setAdjustMode(true);
        commonNavigator.setScrollPivotX(0.25f);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataListButtom == null ? 0 : mDataListButtom.size();
            }

            @Override
            public IPagerTitleView getTitleView(final Context context, final int i) {
                final SimplePagerTitleView clipPagerTitleView = new SimplePagerTitleView(context);
                clipPagerTitleView.setText(mDataListButtom.get(i));
                clipPagerTitleView.setNormalColor(Color.parseColor("#999999"));
                clipPagerTitleView.setSelectedColor(Color.parseColor("#36436a"));
//                clipPagerTitleView.setTextSize(BaseUtils.dip2px(context, 5.2f));
                clipPagerTitleView.setPadding(BaseUtils.dip2px(context, 16.0f), 0, BaseUtils.dip2px(context, 16.0f), 0);

                clipPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (i) {
                            case 0:
                                break;
                            case 1:
                                break;
                        }
//                        magicIndicator.onPageSelected(i);
//                        commonNavigator.onPageSelected(i);
//                        commonNavigator.onAttachToMagicIndicator();
                        viewPager.setCurrentItem(i);
                    }
                });

                return clipPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setColors(new Integer[]{Color.parseColor("#36436a")});
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(BaseUtils.dip2px(context, 2));
                indicator.setLineWidth(BaseUtils.dip2px(context, 60));
                indicator.setRoundRadius(2);
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
//                indicator.setYOffset(UIUtil.dip2px(context, 39));
                return indicator;
            }
        });
        magicIndicatorBotton.setNavigator(commonNavigator);
        LinearLayout titleContainer = commonNavigator.getTitleContainer(); // must after setNavigator
        titleContainer.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        titleContainer.setDividerPadding(UIUtil.dip2px(getActivity(), 0));
        titleContainer.setDividerDrawable(getResources().getDrawable(R.drawable.simple_splitter));
        ViewPagerHelper.bind(magicIndicatorBotton, viewPager);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0 && marketPriceFragment != null) {

                    if (marketPriceFragment.whatBuyRiseOrFall == 0)
                        activity.setBtnTradeTextAndColor(0);
                    else
                        activity.setBtnTradeTextAndColor(1);

                } else if (position == 1) {
                    activity.setBtnTradeTextAndColor(2);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    /**
     * 初始化指示器
     */
    private void initMagicIndicator() {
        final CommonNavigator commonNavigator = new CommonNavigator(getActivity());
        commonNavigator.setRightPadding(UIUtil.dip2px(getActivity(), 40));
        commonNavigator.setScrollPivotX(0.25f);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(final Context context, final int i) {
                final SimplePagerTitleView clipPagerTitleView = new SimplePagerTitleView(context);
                clipPagerTitleView.setText(mDataList.get(i));
                clipPagerTitleView.setNormalColor(Color.parseColor("#666666"));
                clipPagerTitleView.setSelectedColor(Color.parseColor("#36436a"));
                clipPagerTitleView.setTextSize(BaseUtils.dip2px(context, 4.5f));
                clipPagerTitleView.setPadding(BaseUtils.dip2px(context, 16.0f), 0, BaseUtils.dip2px(context, 16.0f), 0);

                clipPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (i == oldPosition) return;
                        oldPosition = i;
                        commonNavigator.onPageSelected(i);
                        commonNavigator.onAttachToMagicIndicator();
                        int position = i;
                        if (position == 0) {
                            isKLine = false;
                            showDialog();
                            timeLineTag = 0;
                            timeDiff = 1000 * 60;
                            presenter.getStockChartData(accessToken, symbolK, "0", 0);
                            MobclickAgent.onEvent(getContext(), "day_time");//友盟统计该点击事件发生次数
                        } else if (position == 1) {
                            isKLine = true;
                            showDialog();
                            timeLineTag = 2;
                            timeDiff = 1000 * 60 * 60 * 24;
                            presenter.getStockChartData(accessToken, symbolK, "1440", 0);
                            MobclickAgent.onEvent(getContext(), "one_day_k");//友盟统计该点击事件发生次数
                        } else if (position == 2) {
                            isKLine = true;
                            timeLineTag = 1;
                            showDialog();
                            timeDiff = 1000 * 60 * 60 * 24 * 7;
                            presenter.getStockChartData(accessToken, symbolK, "10080", 0);

                            MobclickAgent.onEvent(getContext(), "one_minute_k");//友盟统计该点击事件发生次数
                        } else if (position == 3) {
                            isKLine = true;
                            showDialog();
                            timeLineTag = 1;
                            timeDiff = 1000 * 60;
                            presenter.getStockChartData(accessToken, symbolK, "1", 0);
                            MobclickAgent.onEvent(getContext(), "five_minute_k");//友盟统计该点击事件发生次数
                        } else if (position == 4) {
                            isKLine = true;
                            showDialog();
                            timeLineTag = 1;
                            timeDiff = 1000 * 60 * 5;
                            presenter.getStockChartData(accessToken, symbolK, "5", 0);

                            MobclickAgent.onEvent(getContext(), "fifteen_minute_k");//友盟统计该点击事件发生次数
                        } else if (position == 5) {
                            isKLine = true;
                            timeLineTag = 1;
                            showDialog();
                            timeDiff = 1000 * 60 * 15;
                            presenter.getStockChartData(accessToken, symbolK, "15", 0);
                            MobclickAgent.onEvent(getContext(), "thirteen_minute_k");//友盟统计该点击事件发生次数
                        } else if (position == 6) {
                            isKLine = true;
                            timeLineTag = 1;
                            showDialog();
                            timeDiff = 1000 * 60 * 30;
                            presenter.getStockChartData(accessToken, symbolK, "30", 0);

                        } else if (position == 7) {
                            isKLine = true;
                            timeLineTag = 1;
                            showDialog();
                            timeDiff = 1000 * 60 * 60;
                            presenter.getStockChartData(accessToken, symbolK, "60", 0);

                        } else if (position == 8) {
                            isKLine = true;
                            timeLineTag = 1;
                            showDialog();
                            timeDiff = 1000 * 60 * 60 * 4;
                            presenter.getStockChartData(accessToken, symbolK, "240", 0);

                        } else if (position == 9) {
                            isKLine = true;
                            timeLineTag = 1;
                            showDialog();
                            timeDiff = 1000 * 60 * 60 * 24 * 10;
                            presenter.getStockChartData(accessToken, symbolK, "43200", 0);
                        }
                    }
                });

                return clipPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setColors(new Integer[]{Color.parseColor("#36436a")});
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(BaseUtils.dip2px(context, 2));

                return indicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
    }

    /**
     * 昨收、今开、最高、最低
     *
     * @param symbolPrice
     */
    public void setBaseData(SymbolPrice symbolPrice) {
        yestodayClosePrice = symbolPrice.getYesterdayClosePrice();
    }

    /**
     * 盈亏计算及品种保证金相关数据
     *
     * @param symbolInfo
     */
    public void setSymbolCalInfoDatas(SymbolInfo symbolInfo) {
        if (marketAndPendingControlFragment != null) {
//            marketAndPendingControlFragment.setSymbolCalInfoDatas(symbolInfo);
        }
    }

    /**
     * 接收实时价格
     *
     * @param quoteBeen
     */
    public void setRealPrice(List<RealTimeQuoteDatas.DataBean.QuoteBean> quoteBeen) {

        /**
         *实时价格及其变化率
         */
        if (marketAndPendingControlFragment != null)
            marketAndPendingControlFragment.setRealTimeDatas(quoteBeen);
        if (marketPriceFragment != null)
            marketPriceFragment.setRealTimeDatas(quoteBeen);

        if (yestodayClosePrice != -1) {
            double d1 = Arith.sub(quoteBeen.get(0).getMarket(), yestodayClosePrice);
            double d2 = Arith.mul(Arith.div(d1, yestodayClosePrice, 5), 100.0);
        }

        /**
         * 实时修改k线图数据
         */

        Long newTime = quoteBeen.get(0).getTime();
        String n1 = BaseUtils.getDateFromMillionSeconds(newTime);
        newTime = BaseUtils.getMillionSecondsFromDate(n1);
        Double market = quoteBeen.get(0).getMarket();
        String newData = BaseUtils.millionToDate(quoteBeen.get(0).getTime());

        if (newTime - oldTime < timeDiff) {
            oldHigt = Math.max(market, oldHigt);
            oldLow = Math.min(market, oldLow);
            oldClose = market;
            //更改最后一个数据
            changeLastData(newData, quoteBeen.get(0).getTime());
        } else {

            oldTime = newTime;
            oldOpenPrice = market;
            oldHigt = market;
            oldLow = market;
            oldClose = market;

            if (timeLineTag == 0) {
                presenter.getStockChartData(accessToken, symbolK, "0", 1);
            } else {
                //增加一条K线图新数据
                EntrySet entrySett = new EntrySet();
                entrySett.addEntry(new Entry((float) oldOpenPrice, (float) oldHigt, (float) oldLow, (float) oldClose, 0, newData));

                entrySett.computeStockIndex();
                List<Entry> entriess = entrySett.getEntryList();
                kLine.getRender().getEntrySet().addEntries(entriess);
                kLine.notifyDataSetChanged();
            }
        }
    }

    /**
     * 实时更改最后一条数据
     *
     * @param newData
     */
    private void changeLastData(String newData, long newDate2) {
        EntrySet entrySets = new EntrySet();
        if (kLine == null || kLine.getRender() == null) return;
        List<Entry> en = kLine.getRender().getEntrySet().getEntryList();
        if (timeLineTag == 0) {
            if (realDataSize > 0 && en.size() > 1) {
                if (en.size() >= realDataSize)
                    en.remove(realDataSize - 1);
                en.add(realDataSize - 1, new Entry((float) oldOpenPrice, (float) oldHigt, (float) oldLow, (float) oldClose, 0, String.valueOf(newDate2)));
            }
        } else {
            if (realDataSize > 0 && en.size() > 1) {
                en.remove(en.size() - 1);
                en.add(new Entry((float) oldOpenPrice, (float) oldHigt, (float) oldLow, (float) oldClose, 0, newData));
            }
        }

        entrySets.addEntries(en);
        entrySets.computeStockIndex();
        kLine.setEntrySet(entrySets);
        kLine.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void showDialog() {
        if (shortDialog == null && getActivity() != null) {
            shortDialog = new MyProgressDialog(getActivity());
            shortDialog.setCancelable(false);
        }
        shortDialog.show();
    }

    @Override
    public void dismissDialog() {
        if (shortDialog != null && getActivity() != null)
            shortDialog.dismiss();

    }

    @Override
    public void showMyToast(String str) {
        if (getActivity() != null)
            Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void setStockChartData(StockChartDatas stockChartDatas) {

        if (getActivity() == null) {
            Loger.e("ca","!!!");
            return;
        }

        isGetKData = true;
        qb = stockChartDatas.getData().getQuotes();
        int qbSize = qb.size();

        if (qb == null || qb.size() == 0) return;
//                        Collections.reverse(qb);
        oldTime = qb.get(qb.size() - 1).getTime();
        String d1 = BaseUtils.getDateFromMillionSeconds(oldTime);
        oldTime = BaseUtils.getMillionSecondsFromDate(d1);

        oldOpenPrice = qb.get(qb.size() - 1).getOpenPrice();
        oldHigt = qb.get(qb.size() - 1).getHigh();
        oldLow = qb.get(qb.size() - 1).getLow();
        oldClose = qb.get(qb.size() - 1).getClose();
//        tvRealRise.setText(BaseUtils.getDigitsData(qb.get(qb.size() - 1).getClose(), digits));
//        tvRealFall.setText(BaseUtils.getDigitsData(qb.get(qb.size() - 1).getOpenPrice(), digits));



        EntrySet entrySet = new EntrySet();
        final int stockMarkerViewHeight = BaseUtils.dip2px(getActivity(), 15);
        realDataSize = qbSize;
        for (int i = 0; i < qb.size(); i++) {
            Long dataStr = qb.get(i).getTime();
            if (timeLineTag == 0)
                entrySet.addEntry(new Entry((float) qb.get(i).getOpenPrice(), (float) qb.get(i).getHigh(), (float) qb.get(i).getLow(), (float) qb.get(i).getClose(), qb.get(i).getVol(), dataStr + ""));
            else {
                String data = "";
                if (timeLineTag == 1) {
                    data = BaseUtils.millionToMinute(dataStr);
                } else {
                    data = BaseUtils.millionToDay(dataStr);
                }
                entrySet.addEntry(new Entry((float) qb.get(i).getOpenPrice(), (float) qb.get(i).getHigh(), (float) qb.get(i).getLow(), (float) qb.get(i).getClose(), qb.get(i).getVol(), data + ""));
            }
        }
        if (timeLineTag == 0) {
            for (int i = 0; i < 1440 - qbSize; i++)
                entrySet.addEntry(new Entry((float) qb.get(qbSize - 1).getOpenPrice(), (float) qb.get(qbSize - 1).getHigh(), (float) qb.get(qbSize - 1).getLow(), (float) qb.get(qbSize - 1).getClose(), qb.get(qbSize - 1).getVol(), 0 + ""));

        } else if (timeLineTag == -1) {
            for (int i = 0; i < 480 - qbSize; i++)
                entrySet.addEntry(new Entry((float) qb.get(qbSize - 1).getOpenPrice(), (float) qb.get(qbSize - 1).getHigh(), (float) qb.get(qbSize - 1).getLow(), (float) qb.get(qbSize - 1).getClose(), qb.get(qbSize - 1).getVol(), 0 + ""));
        }
        int intDigit = 0;
        if (qb.size() > 0) {
            String str = String.valueOf(qb.get(0).getClose());
            int index = str.indexOf(".");
            if (index != -1) {
                intDigit = index + 1;
            }

        }
        if (isKLine) {//K线图数据
            kLine.setRender(new KLineRender(getActivity(), digits, intDigit));
            entrySet.computeStockIndex();//计算其它附带指标
            kLine.setEntrySet(entrySet);
            KLineRender kr = (KLineRender) kLine.getRender();

            // MACD
            HighlightDrawing macdHighlightDrawing = new HighlightDrawing();
            macdHighlightDrawing.addMarkerView(new YAxisTextMarkerView((int) Utils.convertDpToPixel(10), digits));

//            StockMACDIndex macdIndex = new StockMACDIndex();
//            macdIndex.addDrawing(new MACDDrawing());
//            macdIndex.addDrawing(new StockIndexYLabelDrawing());
//            macdIndex.addDrawing(macdHighlightDrawing);
//            macdIndex.setPaddingTop((int) Utils.convertDpToPixel(10));
//            kr.addStockIndex(macdIndex);

            //下面两行代码可以控制十字线两端是否有文本展示
            kr.addMarkerView(new YAxisTextMarkerView(stockMarkerViewHeight, digits));
            kr.addMarkerView(new XAxisTextMarkerView(stockMarkerViewHeight));


        } else {//分时图数据
            kLine.setRender(new TimeLineRender(timeLineTag, realDataSize, digits, intDigit));
            entrySet.computeStockIndex();
            kLine.setEntrySet(entrySet);
            TimeLineRender tr = (TimeLineRender) kLine.getRender();

            tr.addMarkerView(new YAxisTextMarkerView(stockMarkerViewHeight, digits));
            tr.addMarkerView(new XAxisTextMarkerView(stockMarkerViewHeight));
        }
        kLine.notifyDataSetChanged();
    }

    @Override
    public void setTradeBackInfo(OpenTrader openTrader) {

    }

    @Override
    public void setPendingBackInfo(PendingOrder pendingOrder) {

    }
}
